package com.net;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * Created by chenjinxu on 2019/6/14.
 * 说明:
 */
public class EasyLogInterceptor implements Interceptor {

    private LogCallback logCallback;
    private OnNetErrorCallback netErrorCallback;

    public EasyLogInterceptor() {
    }

    void setLogCallback(LogCallback callback) {
        this.logCallback = callback;
    }

    void setNetErrorCallback(OnNetErrorCallback netErrorCallback) {
        this.netErrorCallback = netErrorCallback;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        String method = "{method=" + request.method()+", url="+request.url()+"}";
        log("请求接口 --> Request"+method);

        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            log("接口返回 <-- HTTP FAILED: " + method+e);
            throw new IOException(method+e);
        }
        if (response.body() == null) {
            if (netErrorCallback != null) {
                netErrorCallback.netError();
            }
            log("接口返回 <-- HTTP ERROR: response null "+method);
            throw new IOException("HTTP ERROR "+ method);
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        ResponseBody responseBody = response.body();
        long contentLength = responseBody.contentLength();
        log("<-- " + response.code() + ' ' + response.message() + ' '
                + " (" + tookMs + "ms" + ')');

        BufferedSource source = responseBody.source();
        try {
            source.request(Long.MAX_VALUE); // Buffer the entire body.
        } catch (Exception e) {
            log("接口返回 <-- HTTP ERROR: source.request(Long.MAX_VALUE) 失败");
            throw new IOException("HTTP ERROR source.request(Long.MAX_VALUE) "+ method);
        }
        Buffer buffer = source.buffer();
        if (contentLength != 0) {
            log("接口返回 <-- " + buffer.clone().readString(StandardCharsets.UTF_8));
        }

        log("<-- END HTTP");

        return response;
    }

    private void log(String msg) {
        if (logCallback != null) {
            logCallback.log("NET", msg);
        }
    }
}